<?php

namespace app\api\controller\sync;

use app\api\controller\Base;
use app\api\controller\Pub;
use app\api\controller\mytool\Sendmessage;
use app\common\model\company\Company;
use app\common\model\orderhawa\Hawa;
use app\common\model\orderhawa\HawaList;
use app\common\model\Sync\SyncCenter;
use app\common\model\user\User as UserModel;

/**
 * 同步中心
 * 创建指令时使用此方法
 *
 */
class Synccreate extends Base
{

    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        // Rolepower::powerguard(203008);
    }

    /**
     * 获取通用的返回需要修改的指令
     * @return [type] [description]
     */
    public static function sysfield(){
        $field = [
            ['name'=>'确认此指令没有重复执行？','key'=>'sys_re_codeisdouble','type'=>'bool'],
            ['name'=>'收集对象信息','key'=>'ssysb_sjdx_select','type'=>'select'],
            ['name'=>'收集记录','key'=>'ssysb_sjjl_select','type'=>'select'],
            ['name'=>'行政区划','key'=>'ssysb_xzqh','type'=>'select'],
            
        ];
        return $field;
    } 

    //---------------------社会源申报--------------------------------------------------------------------------
   
    /**
     * 产废订单创建完后直接执行的
     * @param  SyncCenter $center [description]
     * @return [type]             [description]
     */
    public static function hawaorder($id)
    {
        $data = HawaList::get($id);
        if (empty($data)) {
            return serr('缺少数据');
        }
        if ((int)$data['State'] == HawaList::STATEOK) {
            $data['company'] = Company::get($data['CompanyId']);
            if(SYNC_HB_SSYSB){
                if ($data['company']['IsPlanform'] == 1) {
                    //1没有平台 2已接入平台
                    $sb = self::ssysb_create($data);
                    return $sb;//成功失败都直接返回
                } 
            }else{
                return sok('无需同步');
            }
        }
        return serr('操作失败');
    }

    /**
     * 社会源自主申报 增加记录
     * 货物重量以吨计算
     * @return [type] [description]
     */
    public static function ssysb_create($data)
    {
        if(SYNC_HB_SSYSB_AUTO){
            $type = '社会源收集申报';
        }else{
            $type = '社会源收集申报（保存模块）';
        }

        $sb = SyncCenter::where('Type', $type)->where('ListId', $data['HawaListId'])->find();
        if (!empty($sb)) {
            return serr('同步指令已存在');
        }
        //订单信息
        $ndata['ListId']     = $data['HawaListId'];
        $ndata['Type']       = $type;
        $ndata['Status']     = SyncCenter::STATEINT;
        $ndata['CreateTime'] = date('Y-m-d H:i:s', time());

        $nndata['waretime']    = $data['TransitEndTime']; //货物入库
        $nndata['companyname'] = $data['company']['Name']; //产生单位
        //使用流水号
        if(SYNC_SHYSB_ZDYLSH){
           $nndata['ssysb_zdylsh'] = $data['OrderNumber']; 
        }

        //运输司机信息
        if(!empty($data['TransitDrvierName'])){
            $nndata['TransitDrvierName'] = $data['TransitDrvierName'];
        }

        //车牌号
        if(!empty($data['TransitBrandNumber'])){
            $nndata['TransitBrandNumber'] = $data['TransitBrandNumber'];
        }

        //产废单位具体信息
        if(SYNC_SHYSJSB_INPUTSJDX){
            $nndata['ssysb_csdw'] = $nndata['companyname'];//产生单位
            $nndata['ssysb_xzqh'] = get_address_xzqh($data['company']['Address']);//行政区划
            $nndata['ssysb_sjdd'] = $data['company']['Address']; //收集地点
            $nndata['ssysb_cszrr'] = $data['company']['UserName'];//产生责任人
            $nndata['ssysb_lxdh'] = $data['company']['UserTel'];;//联系电话
            $nndata['ssysb_csdwdz'] = $data['company']['Address']; //产生单位地址
            //如果收集单位责任人身份证
            if(empty($data['company']['UserCard'])){
                if(COMPANYUSERCARD_TYPE=='其他类型'){
                    $nndata['ssysb_cszzrzjhm'] = $data['company']['UserTel'];//产生单位责任人证件号码
                }else{
                     $nndata['ssysb_cszzrzjhm'] = '请输入';//产生单位责任人证件号码
                }
            }else{
                $nndata['ssysb_cszzrzjhm'] = $data['company']['UserCard'];//产生单位责任人证件号码
            }
        }

        $nndata['ssysb_czzrrzjlx'] = COMPANYHAWACARD_TYPE;//产废单位责任人证件类型
        $nndata['ssysb_sjdwfzrzjlx'] = COMPANYUSERCARD_TYPE;//收集单位责任人证件类型
        
        $nndata['ssysb_xkzbh']        = COMPANYNUMBERCARD; //许可证编号
        $nndata['ssysb_sjdwfzr']      = COMPANYUSERNAME; //收集单位负责人
        $nndata['ssysb_sjdwfzrzjh']  = COMPANYUSERCARDNUMBER; //收集单位负责人证件号

        //货物信息
        $nndata['goods'] = [];
        $list            = Hawa::where('HawaListId', $data['HawaListId'])->with(['areainfo', 'goodInfo'])->select();
        foreach ($list as $key => $value) {
            $nndata['goods'][$key] =
                [
                'weight'     => get_xw_sync_weight($value['ReceiveWeight']),
                'use'        => $value['Usage'],
                'goodnumber' => $value['good_info']['OrderNumber'],
                'container'  => $value['Box'],
                'receipt'    => $value['areainfo']['GroupName'] . $value['areainfo']['Name'],
            ];
            //如果有启用货物名称则在数组内添加货物名称选项
            if(SYNC_HB_SSYSB_HAS_GOODNAME){
                $nndata['goods'][$key]['goodname'] = $value['GoodName'];
            }
        }
        //将同步内容转为json
        $ndata['SyncContent'] = json_encode($nndata);
        $sc                   = SyncCenter::create($ndata);
        return Sendmessage::Sync(1, $sc->Id, $sc);
    }

    /**
     * 创建同步指令：
     * 社会源手动获取重量模块
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function ssysb_create_get_data($id)
    {
        $type = '社会源收集申报（手动确认模块）';
        $data = HawaList::get($id);
        if (empty($data)) {
            return serr('缺少数据');
        }
        $data['company'] = Company::get($data['CompanyId']);
        if ($data['company']['IsPlanform'] !== 1) {
            return serr('该企业已在监管平台，无需获取申报数据');
        } 
        $sb = SyncCenter::where('Type', $type)->where('ListId', $data['HawaListId'])->find();
        if (!empty($sb)) {
            return serr('同步指令已存在');
        }
        //订单信息
        $ndata['ListId']     = $data['HawaListId'];
        $ndata['Type']       = $type;
        $ndata['Status']     = SyncCenter::STATESTART;
        $ndata['CreateTime'] = date('Y-m-d H:i:s', time());
        $ndata['UpUserId']   = Pub::userid();

        $nndata['waretime']    = $data['TransitEndTime']; //货物入库
        $nndata['companyname'] = $data['company']['Name']; //产生单位
       
        //货物信息
        $nndata['goods'] = [];
        $list            = Hawa::where('HawaListId', $data['HawaListId'])->with(['areainfo', 'goodInfo'])->select();
        foreach ($list as $key => $value) {
            $nndata['goods'][$key] =
                [
                'weight'     => get_xw_sync_weight($value['ReceiveWeight']),
                'use'        => $value['Usage'],
                'goodnumber' => $value['good_info']['OrderNumber'],
                'container'  => $value['Box'],
                'receipt'    => $value['areainfo']['GroupName'] . $value['areainfo']['Name'],
            ];
            //如果有启用货物名称则在数组内添加货物名称选项
            if(SYNC_HB_SSYSB_HAS_GOODNAME){
                $nndata['goods'][$key]['goodname'] = $value['GoodName'];
            }
        }
        //将同步内容转为json
        $ndata['SyncContent'] = json_encode($nndata);
        $sc                   = SyncCenter::create($ndata);
        $ndata['id']=$sc->Id;
        return sok($ndata);
    }

    /**
     * 社会源申报显示字段
     * @return [type] [description]
     */
    public static function ssysb_view($id)
    {
        //字段名称
        $data['field'] = [
            ['type' => 'date', 'key' => 'waretime', 'name' => '入库时间'],
            ['type' => 'text', 'key' => 'companyname', 'name' => '产废单位名称'],
            ['type' => 'text', 'key' => 'ssysb_xkzbh', 'name' => '许可证编号'],
            ['type' => 'text', 'key' => 'ssysb_sjdd', 'name' => '收集地点'],
            ['type' => 'text', 'key' => 'ssysb_csdw', 'name' => '产生单位'],
            ['type' => 'text', 'key' => 'ssysb_cszrr', 'name' => '产生责任人'],
            ['type' => 'text', 'key' => 'ssysb_lxdh', 'name' => '联系电话'],
            ['type' => 'text', 'key' => 'ssysb_czzrrzjlx', 'name' => '产生责任人证件类型'],
            ['type' => 'text', 'key' => 'ssysb_cszzrzjhm', 'name' => '产生责任人证件号码'],
            ['type' => 'text', 'key' => 'ssysb_csdwdz', 'name' => '产生单位地址'],
            ['type' => 'text', 'key' => 'ssysb_sjdwfzr', 'name' => '收集单位负责人'],
            ['type' => 'text', 'key' => 'ssysb_sjdwfzrzjlx', 'name' => '收集单位负责人证件类型'],
            ['type' => 'text', 'key' => 'ssysb_sjdwfzrzjh', 'name' => '收集单位负责人证件号'],
            ['type' => 'text', 'key' => 'TransitDrvierName', 'name' => '驾驶员姓名'],
            ['type' => 'text', 'key' => 'TransitBrandNumber', 'name' => '车牌号'],
            ['type' => 'text', 'key' => 'ssysb_zdylsh', 'name' => '自定义流水号'],
        ];
        $pubfield = self::sysfield();
        if(!empty($pubfield)){
            $data['field'] = array_merge($pubfield,$data['field']);
        }
        //表格名称
        $data['table']['key']  = 'goods';
        $data['table']['list'] = [
            ['type' => 'text', 'key' => 'goodnumber', 'name' => '危废代码'],
            ['type' => 'text', 'key' => 'goodname', 'name' => '危废名称'],//如果系统没有启用在后面删除 key=1
            ['type' => 'number', 'key' => 'weight', 'name' => '入库重量('.SYNC_WEIGHT.')'],
            ['type' => 'text', 'key' => 'receipt', 'name' => '入库区域'],
            ['type' => 'text', 'key' => 'container', 'name' => '容器类型'],
            ['type' => 'text', 'key' => 'container_rongliang', 'name' => '容器容量'],
            ['type' => 'text', 'key' => 'container_caizhi', 'name' => '容器材质'],
            ['type' => 'text', 'key' => 'use', 'name' => '处置'],
        ];
        //如果没有启用货物名称则在数组内删除货物名称选项
        if(!SYNC_HB_SSYSB_HAS_GOODNAME){
            unset($data['table']['list'][1]);
            $data['table']['list'] = array_values($data['table']['list']);
        }

        $user = UserModel::getinfo();
        if ($user->Role == 203) {
            $data['relationbutton'] = 'orderhawa/orderhawaacco?id=' . $id;
        } else {
            $data['relationbutton'] = 'manaorder/manaorderhawa?id=' . $id;
        }
        return $data;
    }
 //---------------------社会源申报（自动确认模块）--------------------------------------------------------------------------

    /**
     * 社会源自主申报 确认模块
     * 由常量判断是需要自动确认还是手动确认
     * @param  [type] $id   [社会源申报指令id]
     * @param  [type] $data [社会源申报指令数据]
     * @return [type]       [description]
     */
    public static function ssysb_confrim_create($id,$data)
    {   
        //判断手动还是自动确认保存模块
        if(SYNC_HB_SSYSB_CONFRIM_AUTO){
            $type = '社会源收集申报（自动确认模块）';
        }else{
            $type = '社会源收集申报（手动确认模块）';
        }

        $sb = SyncCenter::where('Type', $type)->where('ListId', $data['ListId'])->find();
        if (!empty($sb)) {
            return serr('同步指令已存在');
        }
        //订单信息
        $ndata['ListId']     = $data['ListId'];
        $ndata['Type']       = $type;
        $ndata['Status']     = SyncCenter::STATEINT;
        $ndata['CreateTime'] = date('Y-m-d H:i:s', time());
        //将同步内容转为json
        $ndata['SyncContent'] = $data['SyncContent'];
        $sc                   = SyncCenter::create($ndata);
        return Sendmessage::Sync(1, $sc->Id, $sc);
    }
    
    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
